{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<p> This notebook is meant to be a fun and simple illustration of the <b>Singular Value Decomposition</b>, a tool that is incredibly useful for a lot of data applications. The use cases include dimensionality reduction, recommender systems and data compression. This notebook is an illustration of SVD for data compression, where we examine low-rank approximations of a photograph.\n",
    "\n",
    "\n",
    "</p>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "'''\n",
    "Much thanks to this person for the tutorial on image processing\n",
    "http://nbviewer.ipython.org/gist/frankcleary/4d2bd178708503b556b0\n",
    "'''\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import time\n",
    "from PIL import Image\n",
    "\n",
    "#\n",
    "img = Image.open('C:/Users/kevin/Documents/GitHub/DS_course/datasets/panda.jpg').convert('LA')\n",
    "imgmat = np.array(list(img.getdata(band=0)), float)\n",
    "imgmat.shape = (img.size[1], img.size[0])\n",
    "imgmat = np.matrix(imgmat)\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<p>We've converted the image to black and white and then represented the image as a matrix whose values indicate numeric pixel intensities. Let's plot it just to show that it works. \n",
    "\n",
    "</p>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "plt.imshow(imgmat, cmap='gray')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<p>The SVD decomposition is easy with one line of python code. Remember, with a an $NxM$ matrix $X$, we want to decompose it to: <b>$X=U \\Sigma V^T$</b><br><br>where,<br>\n",
    "\n",
    "<ul>\n",
    "<li> $U$ is $NxM$ and the columns are the orthonormal left singular </li>\n",
    "<li> $\\Sigma$ is $MxM$, is diagonal with the singular values, and the entries are sorted highest to lowest</li>\n",
    "<li> $V$ is $MxM$ and the columns are the orthonormal right singular </li>\n",
    "</ul>\n",
    "\n",
    "(Tip: The following function returns $V^T$ and not $V$)\n",
    "\n",
    "\n",
    "</p>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "U, sig, Vt = np.linalg.svd(imgmat)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<p>Sometimes it is useful to look at the relative magnitude of the singular values to see how much redundency there is in the data. Recall that square root of the total sum-of-squares of the matrix entries (also known as the Frobenius norm \n",
    "$\\|X\\|_F=\\sqrt{\\sum\\limits_{i=1}^N \\sum\\limits_{j=1}^M x_{ij}^2}$) is equal to the same of the singular values. \n",
    "I.e., $\\|X\\|_F=\\sqrt{\\sum\\limits_{i=1}^M \\sigma_i^2}$. <br><br>\n",
    "\n",
    "In the section below, we plot the square root of the total sum-of-squares of the singular values up to the value $k$, normalized by $\\|X\\|_F$ . I.e., $\\frac{\\sqrt{\\sum\\limits_{i=1}^k \\sigma_i^2}}{\\|X\\|_F}$\n",
    "\n",
    "\n",
    "</p>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "#Plot the spectrum of the image and the total sum-squares captured by the k-th value\n",
    "\n",
    "norm = np.sqrt(sum(sig*sig))\n",
    "energy_k = [np.sqrt(k)/norm for k in np.cumsum(sig*sig)]\n",
    "\n",
    "plt.figure()\n",
    "ax1 = plt.subplot(211)\n",
    "plt.plot(sig)\n",
    "plt.title('Kth Singular Value')\n",
    "plt.tick_params(axis='x',which='both',bottom='off',top='off',labelbottom='off')\n",
    "\n",
    "\n",
    "ax2 = plt.subplot(212)\n",
    "plt.plot(energy_k)\n",
    "plt.title('Normalized Cumulative Energy of Kth Singular Value')\n",
    "\n",
    "ax2.set_xlabel('Kth Singular Value')\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<p>If we call the normalized value of $\\sqrt{\\sum\\limits_{i=1}^k \\sigma_i^2}$ the \"cumulative energy\" of the matrix, we can see that for this image, most of the \"energy\" or information in the matrix can be represented with just a few (i.e., way less than 200) singular values/vectors.<br><br>\n",
    "\n",
    "To illustrate this principle, we can form a low rank approximation of the matrix $X$, which we will call $X_k$. This is defined as: $X_k=U_k \\Sigma_k V_k^T$, where for each of the latter 3 matrices we take the first $k$ columns.<br><br>\n",
    "\n",
    "A well known theorem called the <i>Eckart-Young-Mirsky Theorem</i> states that a rank-$k$ approximation using the SVD minimizes the sum-of-squares of the entries of $X-X_k$. Further, the sum-of-squares of the difference between $X$ and $X_k$ (i.e., the Frobenius norm $\\|X-X_k\\|_F$) is given by $\\sqrt{\\sum\\limits_{i=k+1}^{min(M,N)} \\sigma_i^2}$.<br><br>\n",
    "\n",
    "The bottom plot above then shows the normalized $1-\\|X-X_k\\|_F$ for each value $k$. We can see that for this given photo, we can get most of the information in the first dozen or so singular values. Let's see if our eyes agree with this! \n",
    "\n",
    "\n",
    "</p>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "#Now work on an approximate image\n",
    "def plotApprox(U, sig, Vt, k):\n",
    "    reconstimg = np.matrix(U[:, :k]) * np.diag(sig[:k]) * np.matrix(Vt[:k, :])\n",
    "    plt.imshow(reconstimg, cmap='gray');\n",
    "    \n",
    "def plotSeq(U, sig, Vt, seq_k):\n",
    "    fig = plt.figure()\n",
    "    for i,k in enumerate(seq_k[:8]):\n",
    "        ax = fig.add_subplot(2,4,i+1)\n",
    "        plotApprox(U, sig , Vt, k)\n",
    "        plt.title('Rank {}'.format(k))\n",
    "        ax.axes.get_xaxis().set_visible(False)\n",
    "        ax.axes.get_yaxis().set_visible(False)\n",
    "        \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "plotSeq(U,sig,Vt,[1,2,3,4,10,25,50,200])\n",
    "\n",
    "plt.show()\n",
    "\n",
    "#plotApprox(U, sig, Vt, 10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<p>It looks like with a rank of just 4 (out of 200) we can tell it's an animal (but not waht kind). At about 10-25 you might think that they are pandas, but at 50 it becomes clear that they are actually crocodiles.\n",
    "\n",
    "<br><br>\n",
    "\n",
    "And why do we bother with this? If you can get away with a low rank approximation where $k$ is way less than $M$, you can end up saving a considerable amount of space for storing, using, or sending data.\n",
    "\n",
    "</p>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
